package com.it.jzs.service.admin.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.it.jzs.dao.CommentMapper;
//import com.it.jzs.dao.admin.AdminCommentMapper;
import com.it.jzs.pojo.Comment;
import com.it.jzs.pojo.Tag;
import com.it.jzs.pojo.Type;
import com.it.jzs.service.admin.AdminCommentService;
import com.it.jzs.vo.Result;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class AdminCommentServiceImpl implements AdminCommentService {

    @Resource
    private CommentMapper commentMapper;

    @Override
    public Result<Object> selectPage(Integer index, Integer size) { // 分页查询
        QueryWrapper<Comment> wrapper = new QueryWrapper<>();
        Page<Comment> page = new Page<>(index, size);

        Page<Comment> typePage = commentMapper.selectPage(page, wrapper);
        List<Comment> comments = commentMapper.selectList(null);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (Comment comment : comments) {  // 进行时间戳的转换
            Long createTime = comment.getCreateTime();
            Date date = new Date(createTime);
            String format = simpleDateFormat.format(date);
            comment.setFormatTime(format);
        }
        List<Comment> digui = digui(comments, 0);
        return Result.success(digui, "获取分类分页数据成功");

    }


    private List<Comment> digui(List<Comment> comments, Integer pid) {
        List<Comment> list = new ArrayList<>();
        for (Comment comment : comments) {
            if (pid.equals(0)) {
                list.add(comment);
                Integer id = comment.getId();
                List<Comment> digui = digui(comments, id);
                comment.setChildren(digui);
            } else if (comment.getParentCommentId().equals(pid)) {
                list.add(comment);
                Integer id = comment.getId();
                List<Comment> digui = digui(comments, id);
                comment.setChildren(digui);
            }
        }
        return list;
    }

    @Override
    @Transactional
    public Result<Object> delete(Integer id) {
        if (id != null) {
//                Type type = typeMapper.selectById(id);
            int i = commentMapper.deleteById(id);
            if (i > 0) {
                return Result.success(null, "删除成功！");
            }
        }
        return Result.error(null, "删除失败！");
    }
}
